package com.mshen.service;

import java.awt.image.BufferedImage;
import java.util.UUID;
import com.mashen.client.WeiXinClient;
import com.mashen.client.model.MediaResult;
import com.mashen.client.model.QRCodeTicket;
import com.mashen.client.model.UserInfo;
import com.mashen.dao.RecommandDao;
import com.mashen.dao.model.RecommandEntity;
import com.mashen.util.ConfigUtil;
import com.mashen.util.Constant;
import com.mashen.util.ImageUtil;
import com.mashen.util.MessageUtil;
import com.mshen.service.model.ImageResponseMessage;
import com.mshen.service.model.WeixinRequest;

public class CreatePicTask implements Runnable {
	private RecommandDao recomdao;
	private WeixinRequest request;
	public CreatePicTask(WeixinRequest request,RecommandDao recomdao){
		this.request=request;
		this.recomdao=recomdao;
	}
	@Override
	public void run() {
		System.out.println("CreatePicTask start");
		try {
			// 获取用户头像
			UserInfo user = WeiXinClient.getUserInfo(request.getFromUserName());
			System.out.println(user.getHeadimgurl());
			RecommandEntity entity = recomdao.getByOepnid(request
					.getFromUserName());
			if (entity == null) {// 不存在记录，则新增
				entity = new RecommandEntity();
				entity.setOpenid(request.getFromUserName());
				entity.setNickname(user.getNickname());
				entity.setScore(0);// 分数默认为0
				recomdao.add(entity);
			    entity = recomdao.getByOepnid(request.getFromUserName());
			}
			// 生成带参数的二维码
			QRCodeTicket ticket = WeiXinClient.getQRCodeTicket(entity.getID());
			System.out.println(ticket.getTicket());
			String qrcodeurl = ConfigUtil.getValue("qrcodeurl")
					+ ticket.getTicket();
			String bgpath = ConfigUtil.getValue("bgpath");
			BufferedImage bgimage = ImageUtil.getLocalPic(bgpath);
			BufferedImage headimage = ImageUtil.getNetPic(user.getHeadimgurl());
			BufferedImage qrcodeimage = ImageUtil.getNetPic(qrcodeurl);
			ImageUtil.combine(bgimage, headimage, 120, 680, 120, 120);
			ImageUtil.combine(bgimage, qrcodeimage, 320, 680, 120, 120);
			StringBuilder savepath = new StringBuilder(
			ConfigUtil.getValue("imgsavepath"));
			savepath.append(UUID.randomUUID().toString()).append(".jpg");
			ImageUtil.saveImage(bgimage, savepath.toString());
			MediaResult mediars = WeiXinClient.uploadMedia(
			Constant.MSG_TYPE_IMAGE, savepath.toString());
            ImageResponseMessage resp = new ImageResponseMessage();
			resp.setCreateTime(System.currentTimeMillis());
			resp.setToUserName(request.getFromUserName());
			resp.setFromUserName(request.getToUserName());
			resp.setMsgType(Constant.MSG_TYPE_IMAGE);
			resp.setMediaId(mediars.getMedia_id());
			// 判断数据库是否已经存在推荐人记录
			String result = MessageUtil.toXML(resp);
			
			entity.setMediaid(mediars.getMedia_id());
			entity.setPicresult(result);
			recomdao.update(entity);
			System.out.println("CreatePicTask finish");
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
}